<template>
  <div class="business-wrap" >
      <van-pull-refresh v-model="isLoading" @refresh="onRefresh">
        <div class="line-grade-box" >
                <!-- 搜索区/banner -->
                <div
                class="search-area" >
                    <div 
                    @click="handleToCity"
                    class="search-city" >
                        <div class="search-city-name" >{{ city || '请选择' }}</div>
                        <img class="search-city-icon" :src="businessSearchIcon" alt="">
                    </div>
                    <div class="search-box" >
                        <div @click="handleToSearch" class="search-input" >
                            <img class="search-icon" :src="searchIcon" alt="">
                            <div class="search-text" >搜索门店/服务</div>
                            <div class="search-btn" >搜索</div>
                        </div>
                    </div>
                </div>

                <!-- 轮播区 -->
                <van-swipe class="my-swipe" :autoplay="6000" indicator-color="white">
                <van-swipe-item
                v-for="(item, index) in banners"
                :key="index"
                >
                    <img class="banner-li" :src="item.image_url" alt="">
                </van-swipe-item>
                </van-swipe>

                <!-- 分类轮播 -->
                <van-swipe
                class="cate-swipe"  >
                    <van-swipe-item
                    v-for="(item, index) in cate_list"
                    :key="index"
                    >
                        <div class="cate-ul clearfix" >
                            <div 
                            v-for="(pItem, pIndex) in item"
                            :key="pIndex"
                            @click="handleToCate(pItem)"
                            class="cate-li fl" >
                                <img class="cate-li-icon" :src="pItem.icon" alt="">
                                <div class="cate-li-text" >{{ pItem.name }}</div>
                            </div>
                        </div>
                    </van-swipe-item>
                </van-swipe>
        </div>

        <!-- 附近门店 -->
        <div class="shop-vicinity" >
            <div class="shop-vicinity-title" >附近门店</div>
            <div class="shop-tag" >
                <div 
                @click="handleToTag('distance')"
                :class="['shop-tag-li active-btn', distance ? 'on' : '']" >附近门店</div>
                <div 
                @click="handleToTag('new_store')"
                :class="['shop-tag-li active-btn', new_store ? 'on' : '']" >新店</div>
                <div 
                @click="handleToTag('recommend')"
                :class="['shop-tag-li active-btn', recommend ? 'on' : '']" >平台推荐</div>
                <!-- @click="handleToTag('public_status')"联盟补贴 -->
                <div 
                :class="['shop-tag-li active-btn', public_status ? 'on' : '']" style="opacity: 0;">联盟补贴</div>
            </div>
        </div>

        <!-- 店铺列表 -->
            <div v-if="locationBoolean" >
                <van-list
                v-model="loadingPage"
                :finished="finished"
                :finished-text="list.length ? '没有更多了' : ''"
                @load="ajaxGoodList"
                >
                
                    <div v-if="finished && !list.length" class="empty-good" >
                        <van-empty description="暂无店铺" />
                    </div>
                    
                    <!-- 商品列表 -->
                    <!-- 商品列表 -->
                    <div class="good-ul" >
                        <storeGoodItem
                        v-for="(item, index) in list"
                        :key="index"
                        :item="item"
                        @storeInfo="storeInfo"
                        ></storeGoodItem>
                    </div>
                
                </van-list>
            </div>
      </van-pull-refresh>
      <footTab :current="1" ></footTab>
  </div>
</template>

<script>
import footTab from '@/components/foot-tab';
import axios from 'axios';
import storeGoodItem from './components/store-good-item';
import { 
	searchIcon, businessSearchIcon
} from '@/tool/static-img';
import { STORE_HOME_DATA, STORE_LIST } from '@/api/store';
import AMapLoader from '@amap/amap-jsapi-loader';
export default {
    components: {
        footTab,
        storeGoodItem
    },
    data() {
        return {
            searchIcon, businessSearchIcon,
            banners: [],
            cate_list: [],
            typeCurrent: 0,

            // 分页
            page: 1,
            pageSize: 20,
            list: [],
            loadingPage: false,
            finished: false,

            locationBoolean: false,

            // 地址信息
            type: 1, //  0 - 全国  1 - 本地
            latitude: '',
            longitude: '',
            address: '',
            province: '',
            city: '',
            district: '',
            adcode: '',

            // 归属地
            distance: false,
            new_store: false,
            recommend: false,
            public_status: false,

            isLoading: false,


        }
    },
    activated(){
        document.title = '本地商户';
        // 首页数据
        // this.getHomeData();
        this.getHomeData();
        // 手动选择
        const handleCity = localStorage.getItem('handleCity');
        if(handleCity) {
            this.getHandCity(handleCity)
            this.resetInit();
        }else {
            // 缓存中获取 - 12小时
            const locationInfo = localStorage.getItem('locationInfo');
            const latAndLng = localStorage.getItem('latAndLng');
            const optionCity = localStorage.getItem('optionCity');
            if(locationInfo && latAndLng && optionCity) {
                const expressTime = JSON.parse(locationInfo).expressTime;
                const nowTime = new Date().getTime();
                if(nowTime < expressTime) {
                    // 未过期缓存
                    this.adcode = JSON.parse(locationInfo).adcode;
                    this.city = JSON.parse(locationInfo).city;
                    this.type = 1;
                    this.locationBoolean = true;
                    console.log('走缓存定位')
                    return
                }
            }

            // 获取当前位置
            this.getLocation();
        }
    },
    mounted() {


    },
    methods: {
        // 向下刷新
        onRefresh() {
            setTimeout(() => {
                this.isLoading = false;
            }, 500)

            
            // 首页数据
            this.getHomeData();

            // 手动选择
            const handleCity = localStorage.getItem('handleCity');
            if(handleCity) {
                this.getHandCity(handleCity)
                this.resetInit();
            }else {
                // 获取当前位置
                this.getLocation();
            }
        },
        // 城市选择
        handleToCity() {
            this.$router.push({
                name: 'storeCity'
            })
        },
        // 搜索
        handleToSearch() {
            this.$router.push({
                name: 'storeSearch'
            })
        },
        // 城市
        getHandCity(data) {
            const handleCity = JSON.parse(data);
            localStorage.setItem('latAndLng', `${handleCity.latitude},${handleCity.longitude}`);
            this.adcode = handleCity.code;
            this.city = handleCity.name;
            this.type = 0;
            this.locationBoolean = true;
        },
        getLocation() {
            var _this = this;

            window._AMapSecurityConfig = {
                securityJsCode: "638b1bb3fefe982cdf2a8db2cf2a7846",
            };


            // 加载高德地图的定位模块
            AMapLoader.load({
                key: 'ac8b3896464d5d2b7735e62100bee1d0', // 在此处替换为你的高德地图APIKey
                version: '2.0',
                plugins: ['AMap.Geolocation', 'AMap.Geocoder'] // 加载 Geolocation 插件
            }).then((AMap) => {
                const geolocation = new AMap.Geolocation({
                    enableHighAccuracy: true, // 是否使用高精度定位，默认:true
                    useNative: true, // 是否使用安卓定位sdk用来进行定位，需要安卓端sdk配合
                    timeout: 5000,
                    needAddress: true
                });

                var geocoder = new AMap.Geocoder({
                    // city 指定进行编码查询的城市，支持传入城市名、adcode 和 citycode
                    city: '010'
                })

                 geolocation.getCurrentPosition((status, result) => {
                    if (status === 'complete') {
                        localStorage.setItem('latAndLng', `${result.position.lat},${result.position.lng}`);

                        // 如果获取到地址信息
                        if(result.addressComponent && result.addressComponent.adcode) {
                            localStorage.setItem('optionCity', result.addressComponent.city || result.addressComponent.province);

                            _this.adcode  = result.addressComponent.adcode;
                            _this.city = result.addressComponent.city || result.addressComponent.province;
                            _this.type = 1;

                            // 做缓存
                            localStorage.setItem('locationInfo', JSON.stringify({
                                adcode: _this.adcode,
                                city: _this.city,
                                expressTime: new Date().getTime() + 12 * 60 * 60 * 1000
                            }))

                            if(_this.locationBoolean) {
                                // 下拉加载
                                this.resetInit();
                            }else {
                                _this.locationBoolean = true;
                            }
                        }else {
                            // 逆转码
                            let lnglat = [result.position.lng, result.position.lat]
                            geocoder.getAddress(lnglat, function(status, result) {
                                if (status === 'complete' && result.info === 'OK') {
                                    localStorage.setItem('optionCity', result.regeocode.addressComponent.city || result.regeocode.addressComponent.province);

                                    _this.adcode  = result.regeocode.addressComponent.adcode;
                                    _this.city = result.regeocode.addressComponent.city || result.regeocode.addressComponent.province;
                                    _this.type = 1;

                                    // 做缓存
                                    localStorage.setItem('locationInfo', JSON.stringify({
                                        adcode: _this.adcode,
                                        city: _this.city,
                                        expressTime: new Date().getTime() + 12 * 60 * 60 * 1000
                                    }))

                                    if(_this.locationBoolean) {
                                        // 下拉加载
                                        this.resetInit();
                                    }else {
                                        _this.locationBoolean = true;
                                    }
                                }
                            })
                        }
                        
                    } else {
                        onError(result);
                    }
                });
            }).catch((e) => {
                console.error('地图加载失败:', e);
            });
            // 定位出错的回调函数
            function onError(data) {
                _this.$toast('定位失败：请检查是否开通定位权限' )
            }
        },
        // 金刚区
        handleToCate(item) {
            localStorage.removeItem('searchKey');
				this.$router.push({
					name: 'storeList',
					query: {
						cate_id: item.id
					}
				})
        },
        // 首页数据
        getHomeData() {
            this.$http.get(STORE_HOME_DATA)
                .then(res => {
                    const {
                        data
                    } = res;
                    this.banners = data.banners;
                    
                    
                    let len = Math.ceil(data.cate_list.length / 10);
                    let cate_list = [];
                    for(var index = 0; index < len; index++ ) {
                        cate_list[index] = data.cate_list.splice(0, 10)
                    }
                    
                    this.cate_list = cate_list;
                })
        },
        // 店铺列表
        handleToTag(tag) {
            this[tag] = !this[tag];
            this.resetInit();
        },
        resetInit() { //重置
            this.page = 1;
            this.list = [];
            this.finished = false;
            this.loadingPage = true;
            this.ajaxGoodList()
        },
        // 列表请求
        ajaxGoodList() {
            const latAndLng = localStorage.getItem('latAndLng');


            let params = {};
            params['page_num'] = this.page;
            params['page_size'] = this.pageSize;
            if(this.distance) {
                params['distance'] = 10000;
            }

            params['new_store'] = this.new_store ? 1 : 0;
            params['recommend'] = this.recommend ? 1 : 0;
            params['public_status'] = this.public_status ? 1 : 0;
            
            params['type'] = this.type;
            params['longitude'] = latAndLng ? latAndLng.split(',')[1] : '';
            params['latitude'] = latAndLng ? latAndLng.split(',')[0] : '';
            params['region_code'] = this.adcode;

            // 存储 - 搜索列表用
            localStorage.setItem('locationType', this.type);
            localStorage.setItem('locationRegionCode', this.adcode);
            
            this.$http.post(STORE_LIST, params)
            .then(res => {
                const {
                list
                } = res.data;
            
                if(list && list.length) {
                    this.page++;
                    this.list = this.list.concat(list);
                    // 加载状态结束
                    this.loadingPage = false;
                    if(list.length < this.pageSize) {
                    this.finished = true;
                    }
                }else {
                    this.finished = true;
                }
            })
        },
        // 进店铺
        storeInfo(id) {
            const latAndLng = localStorage.getItem('latAndLng');

            this.$router.push({
                name: 'storeInfo',
                query: {
                    id,
                    longitude: latAndLng.split(',')[1],
                    latitude: latAndLng.split(',')[0],
                }
            })
        }

    }

}

</script>
<style lang="scss" >
.business-wrap{
    min-height: 100vh;
    background-color: #f5f5f5;
    padding-bottom: calc(1rem + constant(safe-area-inset-bottom));
    padding-bottom: calc(1rem + env(safe-area-inset-bottom));
    box-sizing: border-box;
    .line-grade-box{
        padding-bottom: 3rem;
        background: linear-gradient( 180deg, #FFFFFF 0%, #FFFFFF 82%, #F5F5F5 100%);
    }
    .search-area{
        display: flex;
        align-items: center;
        padding: 0.08rem 0.24rem 0.28rem;
        box-sizing: border-box;
        .search-city{
            display: flex;
            align-items: center;
            width: 1.3rem;
            margin-right: 0.1rem;
            .search-city-name{
                margin-right: 0.04rem;
                font-weight: 500;
                font-size: 0.28rem;
                color: #333333;
                white-space: nowrap;
                overflow: hidden;
                text-overflow: ellipsis;
                word-break: break-all;
            }
            .search-city-icon{
                width: 0.28rem;
                height: 0.28rem;
            }
        }
        .search-box{
            display: flex;
            align-items: center;
            height: 0.72rem;
            margin: auto;
            .search-input{
				position: relative;
                display: flex;
                align-items: center;
                width: 5.66rem;
                height: 0.72rem;
                border-radius: 0.42rem;
                background-color: #ffffff;
                border: 0.02rem solid #EC2440;
                .search-icon{
                    width: 0.32rem;
                    height: 0.32rem;
                    margin-left: 0.28rem;
                    margin-right: 0.16rem;
                }
                .search-text{
                    height: 0.4rem;
                    line-height: 0.4rem;
                    font-weight: 400;
                    font-size: 0.28rem;
                    color: #c3c3c3;
                }
                .search-btn{
					position: absolute;
					right: 0.06rem;
					top: 0;
					bottom: 0;
					margin: auto;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    width: 1.12rem;
                    height: 0.6rem;
                    margin-left: 1.96rem;
                    font-weight: 400;
                    font-size: 0.28rem;
                    color: #ffffff;
                    border-radius: 0.3rem;
                    background: linear-gradient( 135deg, #FF5851 0%, #E9011B 100%);
                }
            }
            .kefu-icon{
                width: 0.48rem;
                height: 0.48rem;
                margin-left: 0.32rem;
            }
            .help-icon{
                width: 0.48rem;
                height: 0.48rem;
                margin-left: 0.24rem;
            }
        }
    }

    .my-swipe{
        width: 7.02rem;
        height: 2.4rem;
        margin: auto;
        .banner-li{
            width: 100%;
            height: 100%;
            border-radius: 0.16rem;
        }
    }
    .cate-swipe{
        width: 6.6rem;
        padding-top: 0.32rem;
        padding-bottom: 0.3rem;
        margin: auto;
        .van-swipe__indicators{
            bottom: 10px;
            .van-swipe__indicator{
                
                background: #ABABAB;
                transition: all 0.5s;
            }
            .van-swipe__indicator--active{
                width: 18px;
                background: #F32A23;
                border-radius: 3px;
            }
        }
        .cate-ul{
            
            .cate-li{
                margin-right: 0.39rem;
                margin-bottom: 0.16rem;
                &:nth-child(5n) {
                    margin-right: 0;
                }
                .cate-li-icon{
                    display: block;
                    width: 1rem;
                    height: 1rem;
                }
                .cate-li-text{
                    height: 0.34rem;
                    max-width: 1rem;
                    line-height: 0.34rem;
                    font-weight: 400;
                    font-size: 0.24rem;
                    color: #333333;
                    text-align: center;
					white-space: nowrap;
					overflow: hidden;
					text-overflow: ellipsis;
					word-break: break-all;
                }
            }
        }
    }

    .shop-vicinity{
        padding: 0 0.24rem;
        margin-top: -2.8rem;
        margin-bottom: 0.24rem;
        .shop-vicinity-title{
            position: relative;
            height: 0.44rem;
            margin-left: 0.08rem;
            line-height: 0.44rem;
            font-size: 0.32rem;
            font-weight: 600;
            color: #333333;
            &::before{
                position: absolute;
                left: 0;
                bottom: 0;
                content: '';
                width: 1.28rem;
                height: 0.14rem;
                background: linear-gradient( 90deg, #FD1A1A 0%, rgba(231,1,1,0) 100%);
            }
        }

        .shop-tag{
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 0 0.08rem;
            margin-top: 0.24rem;
            .shop-tag-li{
                display: flex;
                align-items: center;
                justify-content: center;
                height: 0.48rem;
                padding: 0 0.32rem;
                font-weight: 400;
                font-size: 0.24rem;
                color: #666666;
                border-radius: 0.24rem;
                border: 0.02rem solid #F2F4F5;
                background: #F2F4F5;
                box-sizing: border-box;
                &.on{
                    background: rgba(243, 42, 35, 0.10);
                    color: #F32A23;
                    border-color: #F32A23;
                }
            }
        }
    }
}
</style>